package com.rp.system.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.rp.system.user.entity.*;
import com.rp.system.user.mapper.SysPermissionMapper;
import com.rp.system.user.model.SysPermissionTree;
import com.rp.system.user.service.SysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rp.system.user.service.SysRoleService;
import com.rp.system.user.service.SysUserService;
import com.rp.common.utils.NullIs;
import com.rp.common.utils.ObjectAndMap;
import com.rp.common.config.redis.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2020-11-24
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private RedisUtil redisUtil;

    public static String KEY_STRING = "shiro:cache:authorizationCache";

    @Override
    public LinkedHashSet<SysPermission> findPermissionsByRoleId(Set<SysRole> roles) {
        return sysPermissionMapper.findPermissionsByRoleId(roles,null);
    }

    @Override
    public List<Tree<String>> findSysPermissionsByUserId(String username) throws IllegalAccessException {
        SysUser user = sysUserService.findSysUserByUsername(username);
        if(NullIs.isEmpty(user)){
            return null;
        }
        //获取用户角色
        Set<SysRole> roles = sysRoleService.findRolesByUserId(user.getId());

        LinkedHashSet<SysPermission> permissions = new LinkedHashSet<SysPermission>();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (!roles.isEmpty()) {
            //添加角色
            for (SysRole role : roles) {
                authorizationInfo.addRole(role.getRoleName());
            }
            //获取用户权限
            permissions.addAll(sysPermissionMapper.findPermissionsByRoleId(roles,true));
        }
        if (!permissions.isEmpty()) {
            //添加权限
            List<Tree<String>> treeList = getTreeList(new ArrayList<>(permissions),true);
            return treeList;
        }
        return null;
    }

    @Override
    public List<Tree<String>> findSysPermissionsByUserIdInCache() throws IllegalAccessException {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        String key = KEY_STRING + ":tree:" + username;
        //缓存存在
        if (redisUtil.hasKey(key)) {
            System.out.println("权限查询直接取缓存数据");
            return (List<Tree<String>>) redisUtil.get(key);
        } else {
            System.out.println("权限查询从数据库查询");
            List<Tree<String>> linkedHashSetList = findSysPermissionsByUserId(username);
            redisUtil.set(key, linkedHashSetList);
            return linkedHashSetList;
        }
    }


    @Override
    public List<Tree<String>> getTreeList(List<SysPermission> list,Boolean IsSysPermissionTree) throws IllegalAccessException {
        //父子树 树状结构  树结构  处理
        List<TreeNode<String>> nodeList = CollUtil.newArrayList();
        for(SysPermission permission : list){
            if(IsSysPermissionTree){
                SysPermissionTree tree = new SysPermissionTree(permission);
                nodeList.add(new TreeNode<>(permission.getId(), permission.getParentId(), tree.getName(), 0).setExtra(ObjectAndMap.objectToMap(tree)));
            }else{
                nodeList.add(new TreeNode<>(permission.getId(), permission.getParentId(), permission.getName(), 0).setExtra(ObjectAndMap.objectToMap(permission)));
            }
        }
        List<Tree<String>> treeList = TreeUtil.build(nodeList, null);
        return treeList;
    }

    @Override
    public LinkedHashSet<SysPermission> getPermissionByDepartOrgCode(String orgCode) {
        return sysPermissionMapper.getPermissionByDepartOrgCode(orgCode);
    }

    @Override
    public LinkedHashSet<SysPermission> getPermissionByDepartParentId(String parentId) {
        return sysPermissionMapper.getPermissionByDepartParentId(parentId);
    }

    @Override
    public List<String> getPermissionPermsByRoleIds(List<String> roleIdList) {
        List<String> list = sysPermissionMapper.getPermissionPermsByRoleIds(roleIdList);
        list.removeAll(Collections.singleton(null));
        list.removeAll(Collections.singleton(""));
        return list;
    }

}
